package com.meaningful.thinking.condition_demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Depot {

    // 仓库里商品数量
    private int count = 0;

    // 仓库最大容量
    private final int capacity = 1;

    private final Lock lock = new ReentrantLock();

    // 仓库不满的等待队列
    private final Condition warehouseFull = lock.newCondition();
    // 仓库不空的等待队列
    private final Condition warehouseEmpty = lock.newCondition();

    // 生产方法
    public void produce() throws InterruptedException {
        lock.lock();
        try {
            while (count == capacity) {
                System.out.println("仓库满了，生产者等待...");
                warehouseFull.await();
            }
            count++;
            System.out.println("生产了一个商品，现在数量：" + count);
            warehouseEmpty.signal(); // 通知消费者有东西了
        } finally {
            lock.unlock();
        }
    }

    // 消费方法
    public void consume() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                System.out.println("仓库空了，消费者等待...");
                warehouseEmpty.await(); // 等待仓库不空
            }
            count--;
            System.out.println("消费了一个商品，现在数量：" + count);
            warehouseFull.signal(); // 通知生产者可以生产了
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Depot depot = new Depot();

        // 消费线程
        new Thread(() -> {
            try {
                while (true) {
                    Thread.sleep(1000);
                    depot.consume();
                }
            } catch (InterruptedException ignored) {
            }
        }).start();

        // 生产线程
        new Thread(() -> {
            try {
                while (true) {
                    Thread.sleep(500);
                    depot.produce();
                }
            } catch (InterruptedException ignored) {
            }
        }).start();
    }

}
